package com.hrsaas.ext.spider.handler;

import com.google.common.net.MediaType;
import com.hrsaas.ext.spider.core.ResponseHandler;
import com.hrsaas.ext.spider.util.JsonUtils;

import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpResponseStatus;

public abstract class JsonResonseHandler<T> extends ResponseHandler<T> {

	@Override
	protected T convert(HttpResponseStatus status, HttpHeaders headers, byte[] content) {
		MediaType mediaType = null;
		if (headers.contains(HttpHeaderNames.CONTENT_TYPE)) {
			try {
				mediaType = MediaType.parse(headers.get(HttpHeaderNames.CONTENT_TYPE));
			} catch (Exception ex) {
				// do nothing
			}
		}
		T result = JsonUtils.fromJson(content, getType());
		if (MediaType.JSON_UTF_8 == mediaType) {
			return result;
		}
		throw new IllegalArgumentException(getConent(content));
	}

}
